<template>
  <div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
    <div class="bg-gray-800 rounded-lg p-6 w-96 max-w-full">
      <!-- 标题和关闭按钮 -->
      <div class="flex justify-between items-center mb-6">
        <h2 class="text-xl font-semibold text-white">{{ isPasswordReset ? '重置密码' : (isLogin ? '登录' : '注册') }}</h2>
        <button @click="$emit('close')" class="text-gray-400 hover:text-white">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
          </svg>
        </button>
      </div>

      <!-- 登录表单 -->
      <div v-if="isLogin && !isPasswordReset">
        <div class="space-y-4">
          <div>
            <label class="block text-sm font-medium text-gray-400 mb-1">用户名</label>
            <input
              v-model="loginForm.username"
              type="text"
              class="w-full px-3 py-2 bg-gray-700 rounded-md text-white focus:outline-none focus:ring-2 focus:ring-[#8153ff]"
              placeholder="请输入用户名"
            >
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-400 mb-1">密码</label>
            <input
              v-model="loginForm.password"
              type="password"
              class="w-full px-3 py-2 bg-gray-700 rounded-md text-white focus:outline-none focus:ring-2 focus:ring-[#8153ff]"
              placeholder="请输入密码"
            >
          </div>
          <!-- 记住我选项 -->
          <div class="flex items-center">
            <input
              id="remember-me"
              v-model="loginForm.rememberMe"
              type="checkbox"
              class="h-4 w-4 text-[#8153ff] focus:ring-[#8153ff] border-gray-500 rounded bg-gray-700"
            >
            <label for="remember-me" class="ml-2 block text-sm text-gray-400">
              记住我
            </label>
            <button 
              @click="isPasswordReset = true" 
              class="ml-auto text-sm text-[#8153ff] hover:underline">
              忘记密码?
            </button>
          </div>
          <button
            @click="handleLogin"
            class="w-full py-2 bg-gradient-to-r from-[#8153ff] to-[#93dc24] text-white rounded-md font-medium hover:opacity-90 transition-opacity"
            :disabled="loading"
          >
            {{ loading ? '登录中...' : '登录' }}
          </button>
        </div>
        <div class="mt-4 text-center">
          <span class="text-gray-400">还没有账号？</span>
          <button @click="isLogin = false" class="text-[#8153ff] hover:underline ml-1">立即注册</button>
        </div>
      </div>

      <!-- 注册表单 -->
      <div v-else-if="!isLogin && !isPasswordReset">
        <div class="space-y-4">
          <div>
            <label class="block text-sm font-medium text-gray-400 mb-1">用户名</label>
            <input
              v-model="registerForm.username"
              type="text"
              class="w-full px-3 py-2 bg-gray-700 rounded-md text-white focus:outline-none focus:ring-2 focus:ring-[#8153ff]"
              placeholder="请输入用户名"
            >
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-400 mb-1">邮箱</label>
            <input
              v-model="registerForm.email"
              type="email"
              class="w-full px-3 py-2 bg-gray-700 rounded-md text-white focus:outline-none focus:ring-2 focus:ring-[#8153ff]"
              placeholder="请输入邮箱"
            >
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-400 mb-1">密码</label>
            <input
              v-model="registerForm.password"
              type="password"
              class="w-full px-3 py-2 bg-gray-700 rounded-md text-white focus:outline-none focus:ring-2 focus:ring-[#8153ff]"
              placeholder="请输入密码"
            >
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-400 mb-1">确认密码</label>
            <input
              v-model="registerForm.confirmPassword"
              type="password"
              class="w-full px-3 py-2 bg-gray-700 rounded-md text-white focus:outline-none focus:ring-2 focus:ring-[#8153ff]"
              placeholder="请再次输入密码"
            >
          </div>
          <button
            @click="handleRegister"
            class="w-full py-2 bg-gradient-to-r from-[#8153ff] to-[#93dc24] text-white rounded-md font-medium hover:opacity-90 transition-opacity"
            :disabled="loading"
          >
            {{ loading ? '注册中...' : '注册' }}
          </button>
        </div>
        <div class="mt-4 text-center">
          <span class="text-gray-400">已有账号？</span>
          <button @click="isLogin = true" class="text-[#8153ff] hover:underline ml-1">立即登录</button>
        </div>
      </div>

      <!-- 密码重置表单 -->
      <div v-else-if="isPasswordReset">
        <div class="space-y-4">
          <div v-if="!resetCodeSent">
            <div>
              <label class="block text-sm font-medium text-gray-400 mb-1">邮箱</label>
              <input
                v-model="resetForm.email"
                type="email"
                class="w-full px-3 py-2 bg-gray-700 rounded-md text-white focus:outline-none focus:ring-2 focus:ring-[#8153ff]"
                placeholder="请输入注册邮箱"
              >
            </div>
            <button
              @click="handleSendResetCode"
              class="w-full py-2 bg-gradient-to-r from-[#8153ff] to-[#93dc24] text-white rounded-md font-medium hover:opacity-90 transition-opacity mt-4"
              :disabled="loading"
            >
              {{ loading ? '发送中...' : '发送验证码' }}
            </button>
          </div>

          <div v-else>
            <div>
              <label class="block text-sm font-medium text-gray-400 mb-1">验证码</label>
              <input
                v-model="resetForm.code"
                type="text"
                class="w-full px-3 py-2 bg-gray-700 rounded-md text-white focus:outline-none focus:ring-2 focus:ring-[#8153ff]"
                placeholder="请输入验证码"
              >
            </div>
            <div class="mt-4">
              <label class="block text-sm font-medium text-gray-400 mb-1">新密码</label>
              <input
                v-model="resetForm.newPassword"
                type="password"
                class="w-full px-3 py-2 bg-gray-700 rounded-md text-white focus:outline-none focus:ring-2 focus:ring-[#8153ff]"
                placeholder="请输入新密码"
              >
            </div>
            <div class="mt-4">
              <label class="block text-sm font-medium text-gray-400 mb-1">确认新密码</label>
              <input
                v-model="resetForm.confirmPassword"
                type="password"
                class="w-full px-3 py-2 bg-gray-700 rounded-md text-white focus:outline-none focus:ring-2 focus:ring-[#8153ff]"
                placeholder="请再次输入新密码"
              >
            </div>
            <button
              @click="handleResetPassword"
              class="w-full py-2 bg-gradient-to-r from-[#8153ff] to-[#93dc24] text-white rounded-md font-medium hover:opacity-90 transition-opacity mt-4"
              :disabled="loading"
            >
              {{ loading ? '重置中...' : '重置密码' }}
            </button>
          </div>
        </div>
        <div class="mt-4 text-center">
          <button @click="backToLogin" class="text-[#8153ff] hover:underline">返回登录</button>
        </div>
      </div>

      <!-- 错误提示 -->
      <div v-if="error" class="mt-4 text-red-500 text-center text-sm">
        {{ error }}
      </div>
      
      <!-- 成功提示 -->
      <div v-if="successMessage" class="mt-4 text-green-500 text-center text-sm">
        {{ successMessage }}
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';

const emit = defineEmits(['close', 'login-success']);

const isLogin = ref(true);
const isPasswordReset = ref(false);
const loading = ref(false);
const error = ref('');
const successMessage = ref('');
const resetCodeSent = ref(false);

const loginForm = reactive({
  username: '',
  password: '',
  rememberMe: false
});

const registerForm = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: ''
});

const resetForm = reactive({
  email: '',
  code: '',
  newPassword: '',
  confirmPassword: ''
});

// 登录处理
async function handleLogin() {
  try {
    loading.value = true;
    error.value = '';
    successMessage.value = '';

    // 模拟API请求 - 实际项目中替换为真实API调用
    // const response = await fetch('http://localhost:3000/api/users/login', {
    //   method: 'POST',
    //   headers: {
    //     'Content-Type': 'application/json'
    //   },
    //   body: JSON.stringify({
    //     username: loginForm.username,
    //     password: loginForm.password,
    //     rememberMe: loginForm.rememberMe
    //   })
    // });
    
    // 模拟成功响应
    const mockResponseData = {
      success: true,
      token: 'mock-jwt-token',
      user: {
        id: 1,
        username: loginForm.username,
        email: 'user@example.com',
        created_at: new Date().toISOString()
      }
    };
    
    // 模拟登录验证
    if (!loginForm.username || !loginForm.password) {
      throw new Error('用户名和密码不能为空');
    }
    
    // 等待一下模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    const data = mockResponseData;

    // 保存token和用户信息到本地存储
    localStorage.setItem('token', data.token);
    localStorage.setItem('user', JSON.stringify(data.user));
    
    // 如果勾选了"记住我"，设置一个长期有效的标记
    if (loginForm.rememberMe) {
      const expiryDate = new Date();
      // 设置为30天后过期
      expiryDate.setDate(expiryDate.getDate() + 30);
      localStorage.setItem('rememberMe', 'true');
      localStorage.setItem('tokenExpiry', expiryDate.toISOString());
    } else {
      localStorage.removeItem('rememberMe');
      localStorage.removeItem('tokenExpiry');
    }

    // 发送登录成功事件
    emit('login-success', data.user);
  } catch (err) {
    error.value = err.message || '登录失败';
  } finally {
    loading.value = false;
  }
}

// 注册处理
async function handleRegister() {
  try {
    // 验证密码
    if (registerForm.password !== registerForm.confirmPassword) {
      error.value = '两次输入的密码不一致';
      return;
    }
    
    if (!registerForm.username || !registerForm.email || !registerForm.password) {
      error.value = '用户名、邮箱和密码不能为空';
      return;
    }

    loading.value = true;
    error.value = '';
    successMessage.value = '';

    // 模拟API请求 - 实际项目中替换为真实API调用
    // const response = await fetch('http://localhost:3000/api/users/register', {
    //   method: 'POST',
    //   headers: {
    //     'Content-Type': 'application/json'
    //   },
    //   body: JSON.stringify({
    //     username: registerForm.username,
    //     email: registerForm.email,
    //     password: registerForm.password
    //   })
    // });
    
    // 模拟成功响应
    const mockResponseData = {
      success: true,
      token: 'mock-jwt-token',
      user: {
        id: Math.floor(Math.random() * 1000) + 1,
        username: registerForm.username,
        email: registerForm.email,
        created_at: new Date().toISOString()
      }
    };
    
    // 等待一下模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    const data = mockResponseData;

    // 注册成功后自动登录
    localStorage.setItem('token', data.token);
    localStorage.setItem('user', JSON.stringify(data.user));

    // 发送登录成功事件
    emit('login-success', data.user);
  } catch (err) {
    error.value = err.message || '注册失败';
  } finally {
    loading.value = false;
  }
}

// 发送重置密码验证码
async function handleSendResetCode() {
  try {
    if (!resetForm.email) {
      error.value = '请输入邮箱地址';
      return;
    }

    loading.value = true;
    error.value = '';
    successMessage.value = '';

    // 模拟API请求 - 实际项目中替换为真实API调用
    // const response = await fetch('http://localhost:3000/api/users/reset-password', {
    //   method: 'POST',
    //   headers: {
    //     'Content-Type': 'application/json'
    //   },
    //   body: JSON.stringify({
    //     email: resetForm.email
    //   })
    // });
    
    // 等待一下模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    // 模拟发送成功
    resetCodeSent.value = true;
    successMessage.value = '验证码已发送到您的邮箱，请查收';
  } catch (err) {
    error.value = err.message || '发送验证码失败';
  } finally {
    loading.value = false;
  }
}

// 重置密码
async function handleResetPassword() {
  try {
    // 验证密码
    if (resetForm.newPassword !== resetForm.confirmPassword) {
      error.value = '两次输入的密码不一致';
      return;
    }
    
    if (!resetForm.code || !resetForm.newPassword) {
      error.value = '验证码和新密码不能为空';
      return;
    }

    loading.value = true;
    error.value = '';
    successMessage.value = '';

    // 模拟API请求 - 实际项目中替换为真实API调用
    // const response = await fetch('http://localhost:3000/api/users/reset-password/confirm', {
    //   method: 'POST',
    //   headers: {
    //     'Content-Type': 'application/json'
    //   },
    //   body: JSON.stringify({
    //     email: resetForm.email,
    //     code: resetForm.code,
    //     newPassword: resetForm.newPassword
    //   })
    // });
    
    // 等待一下模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    // 模拟重置成功
    successMessage.value = '密码重置成功，请使用新密码登录';
    
    // 三秒后返回登录页面
    setTimeout(() => {
      backToLogin();
    }, 3000);
  } catch (err) {
    error.value = err.message || '重置密码失败';
  } finally {
    loading.value = false;
  }
}

// 返回登录页面
function backToLogin() {
  isPasswordReset.value = false;
  resetCodeSent.value = false;
  resetForm.email = '';
  resetForm.code = '';
  resetForm.newPassword = '';
  resetForm.confirmPassword = '';
  error.value = '';
  successMessage.value = '';
}
</script>

<style scoped>
.bg-opacity-50 {
  backdrop-filter: blur(4px);
}
</style> 